package com.example.opencvdemo


import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.platform.LocalContext
import org.opencv.android.Utils
import org.opencv.core.Mat
import org.opencv.imgproc.Imgproc

private const val TAG = "ThresholdCompose"

@Composable
fun ThresholdCompose(modifier: Modifier = Modifier) {
    val context = LocalContext.current
    val bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.pic01)
    val src = Mat()
    val dst = Mat()
    Utils.bitmapToMat(bitmap, src)
    // 先把源文件转为灰度图
    Imgproc.cvtColor(src, dst, Imgproc.COLOR_BGR2GRAY)
    // 设置初始阈值125
    threshold(src, dst, 125.0)
    Column(
        modifier = modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        Image(
            bitmap = bitmap.asImageBitmap(), contentDescription = null
        )
        UpdateModel(modifier, src, dst)
    }
}

@Composable
fun UpdateModel(modifier: Modifier, src: Mat, dst: Mat) {
    var progress by remember { mutableFloatStateOf(125f) }

    val bitmap = threshold(src, dst, progress.toDouble())
    Image(bitmap = bitmap.asImageBitmap(), contentDescription = null)

    Slider(
        value = progress,
        colors = SliderDefaults.colors(
            thumbColor = Color.Red, // 圆圈的颜色
            activeTrackColor = Color(0xFF0079D3)
        ),
        onValueChange = {
            progress = it
        },
        valueRange = 0f..255f,
        steps = 255,
        modifier = modifier.fillMaxWidth(0.8f)
    )
    Text(text = progress.toString())
}

fun threshold(src: Mat, dst: Mat, threshold: Double): Bitmap {
    val bitmap = Bitmap.createBitmap(dst.width(), dst.height(), Bitmap.Config.ARGB_8888)
    Imgproc.threshold(src, dst, threshold, 255.0, Imgproc.THRESH_BINARY)
    Utils.matToBitmap(dst, bitmap)
    return bitmap
}